<template>
  <a-card class="general-card" title="商品列表" :bordered="false">
    <a-tabs
      :default-active-key="goodsStatus"
      @change="changeGoodsStatus"
    >
      <a-tab-pane key="ALL" title="全部"></a-tab-pane>
      <a-tab-pane key="UPPER" title="售卖中"></a-tab-pane>
      <a-tab-pane key="DOWN" title="已下架"></a-tab-pane>
      <a-tab-pane
        key="TOBEAUDITED"
        :title="'审核中（' + waitAuthNum + '）'"
      ></a-tab-pane>
      <a-tab-pane
        key="REFUSE"
        :title="'审核驳回（' + refuseNum + '）'"
      ></a-tab-pane>
      <a-tab-pane key="PASS" title="审核通过"></a-tab-pane>
    </a-tabs>
    <searchTable
      :columns="columnsSearch"
      :row-span="isNormal ? 0 : 12"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    ></searchTable>
    <a-row v-if="isNormal" style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="addGoods"> 添加商品 </a-button>
          <!-- <a-button @click="openImportGoods"> 导入商品 </a-button> -->
          <a-dropdown @select="handleDropdown">
            <a-button> 批量操作 </a-button>
            <template #content>
              <a-doption value="uppers">批量上架</a-doption>
              <a-doption value="lowers">批量下架</a-doption>
              <a-doption value="deleteAll">批量删除</a-doption>
              <a-doption value="batchShipTemplate">批量设置物流模板</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="isNormal ? getGoodsListDataSeller : getGoodsSkuData"
      :page-size="isNormal ? 10 : 6"
      :radio="isNormal ? false : true"
      :bordered="true"
      :checkbox="true"
      :api-params="apiParams"
      @selectTableChange="selectTableChange"
    >
      <template #btnList="{ data }">
        <div>
          <a-space cursor-pointer>
            <a-typography-text
              style="font-size: 12px"
              type="primary"
              @click="
                () =>
                  router.push({
                    name: 'goods-operation',
                    query: { id: data.id },
                  })
              "
            >
              编辑
            </a-typography-text>
          </a-space>
        </div>

        <div>
          <a-space cursor-pointer>
            <a-typography-text
              v-if="data?.marketEnable == 'DOWN'"
              style="font-size: 12px"
              type="primary"
              @click="upper(data)"
            >
              上架
            </a-typography-text>
            <a-typography-text
              v-else
              style="font-size: 12px"
              type="primary"
              @click="lower(data)"
            >
              下架
            </a-typography-text>
          </a-space>
        </div>

        <div>
          <a-space cursor-pointer>
            <a-typography-text
              style="font-size: 12px"
              type="primary"
              @click="getStockDetail(data.id)"
            >
              库存管理
            </a-typography-text>
          </a-space>
        </div>
      </template>
    </tablePage>
    <a-modal
      v-model:visible="shipTemplateModal"
      title="批量设置物流模板"
      ok-text="更新"
      @cancel="shipTemplateModal = false"
      @ok="saveShipTemplate"
    >
      <a-form :model="shipTemplateForm">
        <a-form-item field="templateId" label="物流模板">
          <a-select v-model="shipTemplateForm.templateId">
            <a-option
              v-for="item in logisticsTemplate"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="updateStockModalVisible"
      title="更新库存"
      ok-text="更新"
      @cancel="updateStockModalVisible = false"
      @ok="updateStock"
    >
      <a-tabs>
        <a-tab-pane title="手动规格更新">
          <a-table :columns="updateStockColumns" :data="stockList">
            <template #authFlag="{ rowIndex }">
              <a-tag v-if="stockList[rowIndex].authFlag == 'PASS'" color="green"
                >通过</a-tag
              >
              <a-tag
                v-if="stockList[rowIndex].authFlag == 'TOBEAUDITED'"
                color="blue"
                >待审核</a-tag
              >
              <a-tag v-if="stockList[rowIndex].authFlag == 'REFUSE'" color="red"
                >审核拒绝</a-tag
              >
            </template>
            <template #action="{ rowIndex }">
              <a-input v-model="stockList[rowIndex].quantity" />
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="stockAll" title="批量规格更新">
          <a-input v-model="stockAllUpdate" placeholder="统一规格修改" />
        </a-tab-pane>
      </a-tabs>
    </a-modal>
    <a-modal
      v-model:visible="importModal"
      title="导入商品信息"
      @ok="importOk"
      @cancel="false"
    >
      <div style="text-align: center">
        <a-upload
          :before-upload="handleUpload"
          draggable
          name="files"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :headers="{ accessToken: accessToken }"
          :action="action"
          @change="handleChange"
        >
        </a-upload>
        <a-button type="text" style="color: red" @click="exportGoods"
          >下载导入模板</a-button
        >
      </div>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import {
    batchShipTemplate,
    deleteGoods,
    downLoadGoods,
    getGoodsListDataSeller,
    getGoodsSkuListDataSeller,
    getShipTemplate,
    getGoodsSkuData,
    lowGoods,
    upGoods,
    updateGoodsSkuStocks,
    uploadGoodsExcel,
    getGoodsAuthNum,
  } from '@/api/goods';
  import { onMounted, ref } from 'vue';
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { ColumnsDataRule, SearchRule } from '@/types/global';
  import { gatewayUrl } from '@/utils/axios';
  import store from '@/utils/storage';
  import { authFlag, goodsType, marketEnable, salesModel } from '@/utils/tools';
  import { Message } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  // 组件模式
  const props = defineProps({
    templateModel: {
      type: String,
      default: 'normal',
    },
  });
  const isNormal: boolean = props.templateModel === 'normal';
  const goodsStatus = ref<string>('UPPER');
  // 携带accessToken
  const accessToken = ref<string>(store.getAccessToken() || '');
  const router = useRouter();
  const action = ref<any>('');
  const tablePageRef = ref<any>('');

  const goodsStatusVar = ref<string>('UPPER')
  const apiParams = ref<any>({
    authFlag: 'PASS',
    scene: 'STORE',
    goodsStatus: goodsStatusVar.value,
  })
  const waitAuthNum = ref<any>(0);
  const refuseNum = ref<any>(0);
  const selectList = ref<any>([]);
  const shipTemplateModal = ref<any>(false);
  const shipTemplateForm = ref({}) as any;
  const logisticsTemplate = ref<any>([]); // 物流列表
  const stockList = ref<any>([]); // 库存列表
  const stockAllUpdate = ref<any>(undefined);
  const updateStockModalVisible = ref<any>(false); // 编辑库存模态框
  const importModal = ref<any>(false); // 导入商品模态框
  const ids = ref<string>(''); // 多选行id
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const columnsSearch: Array<SearchRule> = [
    {
      label: '商品名称',
      model: 'goodsName',
      disabled: false,
      input: true,
    },
    {
      label: '商品编号',
      model: 'id',
      disabled: false,
      input: true,
    },
    {
      label: '销售模式',
      model: 'salesModel',
      disabled: false,
      select: {
        options: salesModel,
      },
    },
    {
      label: '商品类型',
      model: 'goodsType',
      disabled: false,
      select: {
        options: goodsType,
      },
    },
    {
      label: '创建时间',
      disabled: false,
      datePicker: {
        type: 'range',
      },
    },
    {
      label: '类目名称',
      model: 'categoryPath',
      disabled: false,
      category: true,
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      slot: true,
      ellipsis: false,
      width: 300,
      fixed: 'left',
      slotData: {
        goods: {
          goodsName: 'goodsName',
          goodsImage: 'original',
        },
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 100,
      currency: true,
    },
    {
      title: '总库存',
      width: 100,
      dataIndex: 'quantity',
    },
    {
      title: '总销量',
      dataIndex: 'buyCount',
      width: 100,
    },
    {
      title: '上架时间',
      dataIndex: 'createTime',
      width: 150,
    },
    {
      title: '商品状态',
      dataIndex: 'marketEnable',
      slot: true,
      width: 100,
      slotData: {
        badge: marketEnable,
      },
    },
  ];

  const sortMethods: any = isNormal
    ? {
        title: '操作',
        width: 100,
        fixed: 'right',
        methods: [
          {
            slot: true,
            slotTemplate: 'btnList',
          },
        ],
      }
    : {};
  const updateStockColumns = [
    {
      title: 'sku规格',
      dataIndex: 'simpleSpecs',
    },
    {
      title: '审核状态',
      slotName: 'authFlag',
    },
    {
      title: '操作',
      slotName: 'action',
    },
  ];
  // 下架
  const lower = (v: any) => {
    modal.confirm({
      title: '确认下架',
      content: `您确认要下架${v.goodsName}?`,
      alignCenter: false,
      onOk: async () => {
        const res = await lowGoods({ goodsId: v.id });
        if (res.data.success) {
          Message.success('下架成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 上架
  const upper = (v: any) => {
    modal.confirm({
      title: '确认上架',
      content: `您确认要上架${v.goodsName}?`,
      alignCenter: false,
      onOk: async () => {
        const res = await upGoods({ goodsId: v.id });
        if (res.data.success) {
          Message.success('上架成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 商品导入
  const importOk = () => {
    importModal.value = false;
    router.go(0);
    tablePageRef.value.init();
  };
  const emit = defineEmits(['selectTableChange']);

  // 选择的行
  const selectTableChange = (val: any) => {
    emit('selectTableChange', { ...val[0], ___type: 'goods' });
    selectList.value = val;
  };
  // 获取物流模板
  const getShipTempList = () => {
    getShipTemplate().then((res: any) => {
      if (res.data.success) {
        logisticsTemplate.value = res.data.result;
      }
    });
  };

  // 获取审核数量
  const getAuthNum = () => {
    getGoodsAuthNum().then((res: any) => {
      if (res.data.success) {
        waitAuthNum.value = res.data.result.waitAuthNum;
        refuseNum.value = res.data.result.refuseNum;
      }
    });
  };
  // 保存物流模板信息
  const saveShipTemplate = () => {
    modal.confirm({
      title: '确认设置物流模板',
      content: `您确认要设置所选的${selectList.value.length}个商品吗？`,
      alignCenter: false,
      onOk: async () => {
        const res = await batchShipTemplate(shipTemplateForm.value);
        if (res.data.success) {
          Message.success('物流模板设置成功');
          shipTemplateModal.value = false;
          tablePageRef.value.init();
        }
      },
    });
  };
  // 获取库存详情
  const getStockDetail = (id: string | number) => {
    getGoodsSkuListDataSeller({ goodsId: id }).then((res: any) => {
      if (res.data.success) {
        stockList.value = res.data.result.records;
        updateStockModalVisible.value = true;
      }
    });
  };
  // 更新库存
  const updateStock = () => {
    const updateStockList = stockList.value.map((item: any) => {
      const j = { skuId: item.id, quantity: item.quantity };
      if (stockAllUpdate.value) {
        j.quantity = stockAllUpdate.value;
      }
      return j;
    });
    updateGoodsSkuStocks(updateStockList).then((res) => {
      if (res.data.success) {
        updateStockModalVisible.value = false;
        Message.success('更新库存成功');
        tablePageRef.value.init();
      }
    });
  };
  // 导入商品
  const openImportGoods = () => {
    importModal.value = true;
    action.value = `${gatewayUrl}/goods/import/import`;
  };

  const handleChange = (fileList: any, fileItem: any) => {
    if (fileItem.status == 'error') {
      Message.error(fileItem.response.message);
    }
  };
  // 下载导入模板
  const exportGoods = () => {
    downLoadGoods()
      .then((res: any) => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        });
        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) {
          // 支持a标签download的浏览器
          const link = document.createElement('a'); // 创建a标签
          link.download = '商品批量导入模板.xls'; // a标签添加属性
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click(); // 执行下载
          URL.revokeObjectURL(link.href); // 释放url
          document.body.removeChild(link); // 释放标签
        } else {
          navigator.msSaveBlob(blob, '商品批量导入模板.xls');
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // 上传数据
  const handleUpload = (file: any) => {
    // file.value = file
    const fd = new FormData();
    fd.append('filed', file);
    uploadGoodsExcel(fd).then((res: any) => {
      if (res.data.success) {
        Message.success('导入成功');
        importModal.value = false;
      }
    });
  };
  // 添加商品
  const addGoods = () => {
    router.push({ name: 'goods-operation' });
  };

  // 批量上架
  const uppers = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要上架的商品');
      return;
    }
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinId = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认上架',
      content: `您确认要上架所选${selectList.value.length}个商品？`,
      alignCenter: false,
      onOk: async () => {
        const res = await upGoods({ goodsId: joinId });
        if (res.data.success) {
          Message.success('上架成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 批量下架
  const lowers = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要下架的商品');
      return;
    }
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinId = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认下架',
      content: `您确定要下架所选的${selectList.value.length}个商品？`,
      alignCenter: false,
      onOk: async () => {
        const res = await lowGoods({ goodsId: joinId });
        if (res.data.success) {
          Message.success('下架成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 批量删除
  const deleteAll = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要删除的商品');
      return;
    }
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinId = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认删除',
      content: `您确定要删除所选的${selectList.value.length}个商品`,
      alignCenter: false,
      onOk: async () => {
        const res = await deleteGoods({ goodsId: joinId });
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 批量设置物流模板
  const batchShipTemplates = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择设置物流模板的商品');
      return;
    }
    getShipTempList();
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinId = ids.value.substring(0, ids.value.length - 1);
    shipTemplateForm.value.goodsId = joinId;
    shipTemplateModal.value = true;
  };
  // 批量操作
  const handleDropdown = (v: any) => {
    // 批量上架
    if (v == 'uppers') {
      uppers();
    }
    // 批量下架
    if (v == 'lowers') {
      lowers();
    }
    // 批量删除商品
    if (v == 'deleteAll') {
      deleteAll();
    }
    // 批量设置物流模板
    if (v == 'batchShipTemplate') {
      batchShipTemplates();
    }
  };


  function changeGoodsStatus(val: string) {
    apiParams.value.goodsStatus = val
    if (val === 'UPPER') {
      apiParams.value.authFlag = 'PASS'
    }
    else {
      apiParams.value.authFlag = ''
    }
  }

  onMounted(() => {
    getAuthNum();
  });
</script>
